<template>
    <div>
        <!-- <div ref="main" id="main" style="width: 100%; height: 300px;border: 3px solid orangered;"></div>
    <img src="./assets/logo.png">
    <router-view /> -->
        <h2>模型名称-版本号(整车车灯-V1)</h2>
        <div style="width: 100%;height: 40px; line-height: 40px; ">
            <div>
                <button @click="impFile">导入</button>
                <input type="file" id="py-file-btn" @change="selectFile($event)" accept=".py" style="display: none;">
                <button @click="setGlobalVar($event)">选择样本数据</button>
                <button @click="runCode">执行测试</button>
                <button>查看结果</button>
                <button @click="output">导出</button>
                <button @click="saveCode">保存</button>
                <button @click="asyncRefresh">获取代码</button>
                <button @click="exit">退出</button>
            </div>
        </div>
        <div id="container">
            <iframe v-if="nbURL" name="ifrmname" id="screenframe" :src="nbURL" frameborder="0" width="100%"
                height="600px"></iframe>
        </div>
    </div>
</template>

<script>
const axios = require('axios').default;
import * as monaco from "monaco-editor";
//this.nbURL = `http://localhost:8888/notebooks/Untitled.ipynb?kernel_name=python3#`
export default {
    name: 'Subpages',
    data() {
        return {
            monacoEditor: null,
            isReload: false,
            timer: null,
            nbURL: '',
            fileName: "",
            bookMode:true
        }
    },
    methods: {
        exit() {
            this.$router.push('/');
        },
        runCode() {
            // axios
            //     .get("http://127.0.0.1:8085/run/" + this.fileName)
            //     .then((data) => {
            //         console.log(data);
            //         console.info("成功")
            //         this.asyncRefresh()
            //     })
            //     .catch((err) => {
            //         console.log(err);
            //     });
            var tarWin=document.getElementById("screenframe").contentWindow
            tarWin.postMessage({
                eventType: 'runcode'
            }, '*')
        },
        saveCode(){
            // //保存代码
            // axios.get("http://127.0.0.1:8888/api/contents/"+ this.fileName)
            // .then(res =>{
            //     let book = res;
            //     console.log(book)
			// 	// book['content'] = {}
			// 	// delete book['last_modified']
			// 	// delete book['created']
			// 	// delete book['mimetype']
			// 	// delete book['size']
			// 	// delete book['writable']
			// 	// delete book['message']
			// 	// book['content']['cells'][0]['source'] = codes;
			// 	// http.put("http://127.0.0.1:8888/api/contents/PPP/"+ this.fileName, book).then(ress => {
			// 	// 	console.info("ress:", ress)
			// 	// })
            // })
            var tarWin=document.getElementById("screenframe").contentWindow
            tarWin.postMessage({
                eventType: 'savebook'
            }, '*')
		},
        setGlobalVar(event) {
            var remote_file =this.GetQueryString("remote_file").toString();
            var filename=remote_file.substring(remote_file.lastIndexOf("/")+1);
            console.log("filename:"+filename)
            var params = {
                "name": filename,
                "path": filename,
                "type": "file",
                "format": "base64",
                "content": "",
                "remote_file": remote_file
            }
            axios.put("http://localhost:8888/api/contents/"+filename,params)
            .then(res =>{
                    console.log(res)
                    if (res.status === 200) {
                        var varName="sysImpGlobalVer"+res.data.name.toString().replace(".","");
                        var msgStr="import pandas as pd\r\nimport json\r\n%who_ls  "+varName+"\r\ncsv_data = pd.read_csv(\"ILNware.csv\", sep = \",\")\r\njsondata=csv_data.to_json(orient = \"index\")\r\n"+varName+" = json.loads(jsondata)";
                        var tarWin = document.getElementById("screenframe").contentWindow
                        tarWin.postMessage({
                            eventType: 'setGlobalVar',
                            msgData:msgStr
                        }, '*')
                    }
            })

        },
        getNBCode(){
            //获取内容
        },
        asyncRefresh() {
            // console.info("准备刷新")
            window.open(document.all.ifrmname.src, 'ifrmname', '')
            // var iframe = document.getElementById("screenframe");
            // iframe.src = iframe.src + "";
            // this.$router.go(0) 
            // this.isLoading = true;
            // if (this.isLoading) {
            //         return;
            //     }
            //     this.$emit('refresh');
            //     this.isLoading = false;
            //     console.info("已经刷新")

        },
        output() {
            // axios.get("http://127.0.0.1:8085/get_file/" + this.fileName.replace('.ipynb', ''), {}, { responseType: 'blob' })
            //     .then((data) => {
            //         console.log(data)
            //         const blob = new Blob([data["data"]])
            //         console.log(blob);
            //         const blobUrl = window.URL.createObjectURL(blob)
            //         console.log(blobUrl);
            //         const a = document.createElement('a')
            //         a.style.display = 'none'
            //         a.download = this.fileName.replace('.ipynb', '') + '.py' // 自定义下载的文件名
            //         a.href = blobUrl
            //         a.click()
            //         window.URL.revokeObjectURL(blob); //释放bolb对象
            //     })
            //     .catch((err) => {
            //         console.log(err);
            //     });
            var tarWin=document.getElementById("screenframe").contentWindow
            tarWin.postMessage({
                eventType: 'exportScript'
            }, '*')
        },
        init() {
            // 使用 - 创建 monacoEditor 对象
            this.monacoEditor = monaco.editor.create(this.$refs.main, {
                theme: "vs-dark", // 主题
                value: "", // 默认显示的值
                language: "javascript",
                folding: true, // 是否折叠
                foldingHighlight: true, // 折叠等高线
                foldingStrategy: "indentation", // 折叠方式  auto | indentation
                showFoldingControls: "always", // 是否一直显示折叠 always | mouseover
                disableLayerHinting: true, // 等宽优化
                emptySelectionClipboard: false, // 空选择剪切板
                selectionClipboard: false, // 选择剪切板
                automaticLayout: true, // 自动布局
                codeLens: false, // 代码镜头
                scrollBeyondLastLine: false, // 滚动完最后一行后再滚动一屏幕
                colorDecorators: true, // 颜色装饰器
                accessibilitySupport: "off", // 辅助功能支持  "auto" | "off" | "on"
                lineNumbers: "on", // 行号 取值： "on" | "off" | "relative" | "interval" | function
                lineNumbersMinChars: 5, // 行号最小字符   number
                enableSplitViewResizing: false,
                readOnly: false, //是否只读  取值 true | false
            });
        },
        selectFile(e){
            var file = e.target.files[0];
            var targetInp = e.target;
            if (file.type !== "text/x-python") {
                alert("非py文件无法上传")
                return;
            } else {
                let reader = new FileReader();
                reader.readAsText(file, 'UTF-8');
                reader.onload = function (e) {
                    let data = "\r\n"+this.result;
                    //console.log(data);
                    targetInp.value = '';
                    var tarWin = document.getElementById("screenframe").contentWindow
                    tarWin.postMessage({
                        eventType: "impPyFile",
                        msgData: data
                    }, '*')
                }
            }
        },
        impFile(){
            document.getElementById('py-file-btn').click();
        },
        GetQueryString(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
            var r = window.location.search.substring(1).match(reg); //获取url中"?"符后的字符串并正则匹配
            var context = "";
            if (r != null)
                context = decodeURIComponent(r[2]);
            reg = null;
            r = null;
            return context == null || context == "" || context == "undefined" ? "" : context;
        }

    },
    created() {
        var that=this;
        console.info("初始化： ")
        if(that.GetQueryString("bookMode")==="true"){
            that.bookMode=true;
        }else{
            that.bookMode=false;
        }
        
        //console.info(this.$route.query)
        //this.fileName = this.$route.query.fileName
        this.$nextTick(() => {
            let iframe = document.getElementById('screenframe')
            let iframeLoad = function () {
                //在此写业务逻辑
                //console.log('加载完了!')
                setTimeout(() => {
                    //alert(that.bookMode)
                    //console.log("vue:postMessage")
                    var tarWin = document.getElementById("screenframe").contentWindow
                    tarWin.postMessage({
                        eventType: 'bookMode',
                        msgData: that.bookMode
                    }, '*')
                }, 1000);
            }
            if (!iframe.addEventListener) {
                iframe.attachEvent('onload', iframeLoad)
            }
            iframe.addEventListener('load', iframeLoad, true)
        })

        this.fileName ="Untitled.ipynb"
        this.nbURL = `http://localhost:8888/notebooks/Untitled1.ipynb?factory=Notebook`
    }
}

</script>


<style>
#top-panel {
    display: none;
}
</style>
